﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OpenGiving;
using System.Web.Security;

public partial class EventForm : System.Web.UI.UserControl
{
    private static string newDummyId = "{NEW}";

    private bool _readOnly = false;

    /// <summary>
    /// Whether this form will support updates
    /// </summary>
    public bool ReadOnly
    {
        get
        {
            return _readOnly;
        }
        set
        {
            _readOnly = value;

            lblID.Enabled = _readOnly;
            ddlContacts.Enabled = _readOnly;
            ddlHoods.Enabled = _readOnly;
            ddlOrgs.Enabled = _readOnly;

            tbName.Enabled = _readOnly;
            tbBriefDesc.Enabled = _readOnly;
            tbFullDesc.Enabled = _readOnly;
            //calStartDate.Enabled = _readOnly;
            tbStart.Enabled = _readOnly;
            tbEnd.Enabled = _readOnly;

            tbNeeded.Enabled = _readOnly;
            tbMax.Enabled = _readOnly;
            cbSameDay.Enabled = _readOnly;
            tbUrl.Enabled = _readOnly;

            tbStreet.Enabled = _readOnly;
            tbCity.Enabled = _readOnly;
            ddlState.Enabled = _readOnly;
            tbPostal.Enabled = _readOnly;

            btnSave.Visible = _readOnly;
            btnNew.Visible = _readOnly;
            btnCancel.Visible = _readOnly;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ReadOnly = Request.IsAuthenticated && Roles.IsUserInRole("Admin");

        // Possibly auto-fill form on a GET
        if (!Page.IsPostBack)
        {
            string event_id = Request["event_id"];
            if (string.IsNullOrEmpty(event_id)) LoadEvent(-1);
            else
            {
                short id;
                if (Int16.TryParse(event_id, out id)) LoadEvent(id);
            }
        }
    }

    private void LoadEvent(int id)
    {
        if (id == -1)
            ClearEventForm();
        else
            LoadKnownEvent(id);
    }

    private void LoadKnownEvent(int id)
    {
        using (OpenGivingDataContext db = new OpenGivingDataContext())
        {
            Events ev = db.Events.Where(x => x.event_id == id).FirstOrDefault();
            if (ev == null)
            {
                // Bad event ID
                Response.Redirect(Page.AppRelativeVirtualPath);
            }
            else
            {
                lblID.Text = id.ToString();
                ddlContacts.SelectedValue = ev.UserMappings.contact_id.ToString();
                ddlHoods.SelectedValue = ev.Neighborhoods.neighborhood_id.ToString();
                ddlOrgs.SelectedValue = ev.Organizations.organization_id.ToString();

                tbName.Text = ev.eventName;
                tbBriefDesc.Text = ev.briefDescription;
                tbFullDesc.Text = ev.fullDescription;
                calStartDate.Date = ev.startTime.Date;
                tbStart.Text = ev.startTime.ToShortTimeString();
                tbEnd.Text = ev.endTime.ToShortTimeString();

                tbNeeded.Text = ev.volunteerMax.ToString();
                tbMax.Text = ev.registrationCutOff.ToString();
                cbSameDay.Checked = ev.sameDayRegistration;
                tbUrl.Text = ev.url;

                tbStreet.Text = ev.address_street;
                tbCity.Text = ev.address_city;
                ddlState.Text = ev.address_state;
                tbPostal.Text = ev.address_zip;
                //ev.address_country = "US";
            }
        }
    }

    private void ClearEventForm()
    {
        lblID.Text = newDummyId;
        ddlContacts.SelectedValue = "";
        ddlHoods.SelectedValue = "";
        ddlOrgs.SelectedValue = "";

        tbName.Text = "{New Event}";
        tbBriefDesc.Text = "";
        tbFullDesc.Text = "";
        calStartDate.Date = DateTime.Now.Date;
        tbStart.Text = "12:00pm";
        tbEnd.Text = "5:00pm";

        tbNeeded.Text = "0";
        tbMax.Text = "0";
        cbSameDay.Checked = true;
        tbUrl.Text = "";

        tbStreet.Text = "";
        tbCity.Text = "";
        ddlState.Text = "";
        tbPostal.Text = "";
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        using (OpenGivingDataContext db = new OpenGivingDataContext())
        {
            Events ev;

            if (string.IsNullOrEmpty(lblID.Text) || lblID.Text == newDummyId) ev = new Events();
            else
            {
                int id = Int32.Parse(lblID.Text);
                ev = db.Events.Where(x => x.event_id == id).FirstOrDefault();
            }

            int key = Int32.Parse(ddlContacts.SelectedValue);
            ev.UserMappings = db.UserMappings.Where(x => x.contact_id == key).FirstOrDefault();

            key = Int32.Parse(ddlHoods.SelectedValue);
            ev.Neighborhoods = db.Neighborhoods.Where(x => x.neighborhood_id == key).FirstOrDefault();

            key = Int16.Parse(ddlOrgs.SelectedValue);
            ev.Organizations = db.Organizations.Where(x => x.organization_id == key).FirstOrDefault();

            ev.eventName = tbName.Text;
            ev.briefDescription = tbBriefDesc.Text;
            ev.fullDescription = tbFullDesc.Text;
            DateTime d = calStartDate.Date;
            ev.startTime = DateTime.Parse(d.ToShortDateString() + " " + tbStart.Text);
            ev.endTime = DateTime.Parse(d.ToShortDateString() + " " + tbEnd.Text);

            ev.volunteerMax = Byte.Parse(tbNeeded.Text);
            ev.registrationCutOff = short.Parse(tbMax.Text);
            ev.sameDayRegistration = cbSameDay.Checked;
            ev.url = tbUrl.Text;

            ev.address_street = tbStreet.Text;
            ev.address_city = tbCity.Text;
            ev.address_state = ddlState.Text;
            ev.address_zip = tbPostal.Text;
            ev.address_country = "US";

            db.Events.InsertOnSubmit(ev);
            db.SubmitChanges();

            Page.MessageBox("New event \"" + ev.eventName + "\" has been created", "~/Admin/Default.aspx");
        }
    }
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Response.Redirect(Page.AppRelativeVirtualPath);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        // Load a new event (blank the form)
        LoadEvent(-1);
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        // We use today's date here in case they haven't selected a date yet
        // We only care about the time here
        DateTime start = DateTime.Parse(DateTime.Today.ToShortDateString() + " " + tbStart.Text);
        DateTime end = DateTime.Parse(DateTime.Today.ToShortDateString() + " " + tbEnd.Text);
    }

    protected void btnCancelEvent_Click(object sender, EventArgs e)
    {
        using (OpenGivingDataContext db = new OpenGivingDataContext())
        {
            Events ev;

            if (!string.IsNullOrEmpty(lblID.Text) && lblID.Text != newDummyId)
            {
                int id = Int32.Parse(lblID.Text);
                ev = db.Events.Where(x => x.event_id == id).FirstOrDefault();
                ev.isCancelled = true;
                db.SubmitChanges();
                Page.MessageBox("Event has been cancelled", "~/Admin/Default.aspx");
            }

        }
    }
}
